﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using mtTools;
using System.Web.Caching;
using System.Threading.Tasks;
using System.Text;

namespace mtWebDraw.Common
{
    /// <summary>
    /// 缓存自动化操作类
    /// </summary>
    public class Cached
    {

        /// <summary>
        /// 缓存自动化操作方法
        /// </summary>
        /// <typeparam name="T">缓存数据类型</typeparam>
        /// <param name="key">缓存key</param>
        /// <param name="getData">缓存数据新取方法</param>
        /// <param name="isCaching">判断新取数据是否有效，null不需要判断</param>
        /// <param name="absoluteMinutes">缓存过期时间（分钟）【该时长一到则强制过期】</param>
        /// <param name="isFileCaching">是否进行文件缓存，是则新取时写入缓存文件以备新取失败时读取返回</param>
        /// <param name="dependencies">缓存文件依赖项或缓存key依赖项，无则null【任何依赖项更改时过期并移除】</param>
        /// <returns></returns>
        public static T Caching<T>(string key, Func<T> getData, Func<T, bool> isCaching, int absoluteMinutes, bool isFileCaching = false, CacheDependency dependencies = null) where T : class
        {
            var value = CacheHelper.GetCache(key);
            if (value != null)
                return value as T;

            T obj = default(T);
            bool iscach = false;
            try
            {
                obj = getData();
                iscach = isCaching(obj);
            }
            catch (Exception ex)
            {
                ex.WriteFile("Cached.Caching", "key:" + key);
            }

            string filePath = LogHelper.appPath + "Cached\\" + key + ".cache";
            if (iscach)
            {
                CacheHelper.InsertCache(key, obj, absoluteMinutes, dependencies);

                if (isFileCaching) //有文件缓存时写入缓存文件内容
                {
                    Task t = new Task(() =>
                    {
                        FileHelper.WriteText(filePath, obj.JSONSerialize(), TextWriteType.Covered, Encoding.UTF8);
                    });
                    t.Start();
                }
            }
            else if (isFileCaching) //当新取数据不符合缓存条件并且有文件缓存时读取缓存文件内容返回
            {
                var tempStr = FileHelper.ReadText(filePath, Encoding.UTF8);
                if (!tempStr.IsNullOrWhiteSpace())
                    obj = tempStr.JSONDeserialize<T>();
            }

            return obj;
        }

    }
}